package com.workerhelping.controller;

import com.workerhelping.constant.MQConstant;
import com.workerhelping.dto.AssistDTO;
import com.workerhelping.dto.AssistInfoDTO;
import com.workerhelping.dto.ESAssistInfoDTO;
import com.workerhelping.dto.RabbitMQDTO;
import com.workerhelping.elasticsearchEntity.ESAssistVO;
import com.workerhelping.elasticsearchEntity.ESRecordVO;
import com.workerhelping.enums.IncomeCategoryEnum;
import com.workerhelping.feignClients.ESFeignClient;
import com.workerhelping.feignClients.MySQLFeignClient;
import com.workerhelping.feignClients.RabbitMQFeignClient;
import com.workerhelping.po.Assist;
import com.workerhelping.po.IncomeCategory;
import com.workerhelping.result.Result;
import com.workerhelping.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/assist")
public class AssistController {
    @Autowired
    private MySQLFeignClient mySQLFeignClient;

    @Autowired
    private RabbitMQFeignClient rabbitMQFeignClient;

    @Autowired
    private ESFeignClient esFeignClient;

    /**
     * 获取所有已通过档案
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Deprecated
    @GetMapping("/getAllByApproved")
    public Result<Object> getAllByApproved(@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                           @RequestParam(value = "pageSize", required = false, defaultValue = "6") Integer pageSize) {
        Result<Object> findResult = mySQLFeignClient.getAllByApproved(pageNo, pageSize);
        if (!findResult.isOk())
            return Result.fail();
        Object records = findResult.getData();
        if (StringUtils.isEmpty(records))
            return Result.build(null, ResultCodeEnum.DATA_IS_EMPTY);
        return Result.ok(records);
    }


    /**
     * 获取所有已通过档案
     * - 聚合搜索
     *  - id:精准匹配
     *  - name:模糊查询，三字-五字允许一个容错
     *  - idNumber:通配符查询
     *  - creditCardNumber:通配符查询
     * @param id
     * @param name
     * @param idNumber
     * @param creditCardNumbers
     * @return
     */
    @GetMapping("/searchByApproved")
    Result<List<ESRecordVO>> findAllByApproved(@RequestParam(value = "sId", required = false) Integer id,
                                               @RequestParam(value = "sName", required = false) String name,
                                               @RequestParam(value = "sIdNumber", required = false) String idNumber,
                                               @RequestParam(value = "sCreditCardNumbers", required = false) String creditCardNumbers) {
        Result<List<ESRecordVO>> recordsResult = esFeignClient.findAllByApproved(id, name, idNumber, creditCardNumbers);
        if (!recordsResult.isOk())
            return Result.fail();
        List<ESRecordVO> records = recordsResult.getData();
        if (records.isEmpty())
            return Result.build(null, ResultCodeEnum.DATA_IS_EMPTY);
        return Result.ok(records);
    }

    /**
     * 发放补助
     *
     * @param assistDTO 职工id 发放类别id 个人发放金额
     * @return
     */
    @PostMapping("/assist")
    Result<String> assist(@RequestBody AssistDTO assistDTO) {
        log.info(assistDTO.toString());
        double targetPrice = assistDTO.getWorkerId().size() * assistDTO.getPrice();
        Result<IncomeCategory> getResult = mySQLFeignClient.getCategoryById(assistDTO.getCategoryId());
        IncomeCategory incomeCategory = getResult.getData();
        String category = incomeCategory.getCategory();
        double remain = incomeCategory.getCount();
        if (targetPrice > remain)
            return Result.build(222, category + "当前剩余" + remain + "元,不足以支持本次发放!");
        else {
            Result<String> updateResult = mySQLFeignClient.descIncome(assistDTO);
            if (!updateResult.isOk())
                return Result.fail();
            ArrayList<Assist> assistsInfos = new ArrayList<>();
            ArrayList<ESAssistVO> esAssistsInfos = new ArrayList<>();
            for (Integer workerId : assistDTO.getWorkerId()) {
                Assist assist = new Assist(
                        new Date(),
                        assistDTO.getYear(),
                        assistDTO.getPrice(),
                        assistDTO.getCategoryId(),
                        workerId
                );
                // 构造es对象
                ESAssistVO esAssist = new ESAssistVO(
                        null,
                        new Date(),
                        assistDTO.getYear(),
                        assistDTO.getPrice(),
                        IncomeCategoryEnum.getCategoryName(assistDTO.getCategoryId()),
                        workerId
                );
                assistsInfos.add(assist);
                esAssistsInfos.add(esAssist);
            }
            AssistInfoDTO assistInfoDTO = new AssistInfoDTO(assistsInfos);
            ESAssistInfoDTO esAssistInfoDTO = new ESAssistInfoDTO(esAssistsInfos);
            Result<String> insertResult = mySQLFeignClient.insertAssistInfo(assistInfoDTO);
            if (!insertResult.isOk())
                return Result.fail();
            // 构造rabbitMQDTO对象，用于更新es索引
            RabbitMQDTO rabbitMQDTO = new RabbitMQDTO(
                    MQConstant.EXCHANGE_ASSIST,
                    MQConstant.ROUTINGKEY_ASSIST_INSERT,
//                    esAssistInfoDTO
                    esAssistsInfos
            );
            rabbitMQFeignClient.sendMsg(rabbitMQDTO);
            return Result.ok();
        }
    }
}
